package org.example.day03;

/**
 * 第二章节2.1.4:synchronized方法与锁对象
 **/
public class MyThread5 {
    synchronized public void methodA(){
        try {
            System.out.println("begin methodA, threadName = " + Thread.currentThread().getName());
            Thread.sleep(5000);
            System.out.println("end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyThread5 m5 = new MyThread5();
        Thread5A a = new Thread5A(m5);
        a.setName("a");
        Thread5B b = new Thread5B(m5);
        b.setName("b");
        a.start();
        b.start();
    }
}

class Thread5A extends Thread{
    private MyThread5 m5;

    public Thread5A(MyThread5 m5) {
        this.m5 = m5;
    }

    @Override
    public void run() {
        m5.methodA();
    }
}

class Thread5B extends Thread{
    private MyThread5 m5;

    public Thread5B(MyThread5 m5) {
        this.m5 = m5;
    }

    @Override
    public void run() {
        m5.methodA();
    }
}

//不加synchronized修饰methodA
//begin methodA, threadName = a
//begin methodA, threadName = b
//end
//end

//加synchronized修饰methodA
//begin methodA, threadName = a
//end
//begin methodA, threadName = b
//end